/**
 * @author ZhiWen Ren
 * @version 1.0
 * @description: LeetCode-72-编辑距离
 * @date 2025/8/26 14:59
 */
public class Solution72 {
    public int minDistance(String word1, String word2) {
        int m = word1.length(), n = word2.length();
        int[][] dp = new int[m + 1][n + 1];

        // 初始化dp数组
        for (int i = 1; i <= m; i++) {
            dp[i][0] = i;
        }
        for (int j = 1; j <= n; j++) {
            dp[0][j] = j;
        }

        // 左，上，左上，三种情况选择最小填充dp数组
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                int left = dp[i][j - 1] + 1, up = dp[i - 1][j] + 1;
                int leftUp;
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    leftUp = dp[i - 1][j - 1];
                } else {
                    leftUp = dp[i - 1][j - 1] + 1;
                }
                dp[i][j] = Math.min(leftUp, Math.min(left, up));
            }
        }

        return dp[m][n];
    }
}
